import socket
import threading

def readmsg(conn,username,list):

    list.append((conn,username))
    login = '客户端：'+username[0:-1] + '已上线'
    for sock in socks:
        sock[0].send(login.encode('utf-8'))
    while True:
        data=conn.recv(1024)
        if len(data)!=0:
            if data.decode('utf-8') =='exit':
                exituser=None
                exiemsg=None
                for sock in socks:
                    if sock[0]==conn:
                        list.remove(sock)
                        exituser = '客户端：{0}已退出服务器。'.format(sock[1][0:-1])
                        exiemsg ='{0}已退出服务器。'.format(sock[1][0:-1])
                for sock in socks:
                    sock[0].send(exituser.encode('utf-8'))
                print(exiemsg)
                conn.send('退出成功'.encode('utf-8'))
            else:
                for sock in socks:
                    if sock[0]==conn:
                        talk=sock[1]+data.decode('utf-8')
                        print(talk)
                for sock in socks:
                    if sock[0]!=conn:
                        if len(talk)!=0:
                            sock[0].send(talk.encode('utf-8'))

ip=('129.211.74.183',9798)
socks = []

s1=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s1.bind(ip)
print('ip绑定成功!')
s1.listen(5)
while True:
    conn,addr=s1.accept()
    name=conn.recv(1024).decode('utf-8')
    if name == None:
        name='无名氏'
    username=name+':'
    if len(name)!=0:
        print('{0}连接成功,用户名：{1}'.format(addr,name))
        msgread = threading.Thread(target=readmsg, args=(conn,username,socks))
        msgread.start()




